package com.sright.bcard.content.biz.manager.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sright.bcard.common.biz.manager.ContentCheckManager;
import com.sright.bcard.common.service.share.constants.SystemConstants;
import com.sright.bcard.common.service.share.dto.common.CheckImageDTO;
import com.sright.bcard.common.service.share.dto.common.CheckResultDTO;
import com.sright.bcard.common.service.share.dto.component.ComponentCufaceMaterialConfigComponentDTO;
import com.sright.bcard.common.service.share.dto.content.*;
import com.sright.bcard.common.service.share.dto.pager.Pager;
import com.sright.bcard.common.service.share.dto.request.CardEditDetailRequest;
import com.sright.bcard.common.service.share.dto.request.CardEditRequest;
import com.sright.bcard.common.service.share.dto.request.EnterpriseCardRequest;
import com.sright.bcard.common.service.share.dto.request.TextCheckRequest;
import com.sright.bcard.common.service.share.dto.response.CardListResponse;
import com.sright.bcard.common.service.share.dto.response.EnterpriseCardDetailResponse;
import com.sright.bcard.common.service.share.dto.response.CardMaterialResponse;
import com.sright.bcard.common.service.share.dto.response.EnterpriseCardResponse;
import com.sright.bcard.common.service.share.enums.*;
import com.sright.bcard.common.service.share.exception.base.BusinessErrorException;
import com.sright.bcard.common.service.share.exception.code.BusinessCode;
import com.sright.bcard.common.service.share.okhttp.serial.SerialUtil;
import com.sright.bcard.common.service.share.utils.AliyunUitls;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.common.service.share.utils.DateTimeUtils;
import com.sright.bcard.common.share.service.ContentCheckService;
import com.sright.bcard.component.dal.dao.ComponentCufaceMaterialConfigComponentDAO;
import com.sright.bcard.component.dal.entity.ComponentCufaceMaterialConfigComponentDO;
import com.sright.bcard.content.biz.manager.CardManager;
import com.sright.bcard.content.biz.manager.strategy.Context;
import com.sright.bcard.content.biz.manager.strategy.impl.CardFullStrategy;
import com.sright.bcard.content.dal.dao.*;
import com.sright.bcard.content.dal.entity.*;
import com.sright.bcard.content.dal.result.EnterpriseCardResult;
import com.sright.bcard.content.dal.result.CardListDTO;
import com.sright.bcard.content.share.request.CardParamRequest;
import com.sright.bcard.content.share.request.CardSaveParam;
import com.sright.bcard.content.share.request.EnterpriseCardAddParam;
import com.sright.bcard.content.share.service.TextCheckService;
import com.sright.bcard.enterprise.dal.dao.AddressDAO;
import com.sright.bcard.enterprise.dal.dao.CompanyDAO;
import com.sright.bcard.enterprise.dal.dao.EnterpriseDAO;
import com.sright.bcard.enterprise.dal.entity.AddressDO;
import com.sright.bcard.enterprise.dal.entity.CompanyDO;
import com.sright.bcard.enterprise.dal.entity.EnterpriseDO;
import com.sright.bcard.common.service.share.dto.enterprise.IndustryDTO;
import com.sright.bcard.enterprise.share.service.EnterpriseService;
import com.sright.bcard.user.dal.dao.CardConnectUserInfoDAO;
import com.sright.bcard.user.dal.dao.MemberDAO;
import com.sright.bcard.user.dal.entity.CardConnectUserInfoDO;
import com.sright.bcard.user.dal.entity.MemberDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CardManagerImpl implements CardManager {

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private CardFullStrategy cardFullStrategy;

    @Autowired
    private CardUserInfoDAO cardUserInfoDAO;

    @Autowired
    private AddressDAO addressDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private CompanyDAO companyDAO;

    @Autowired
    private CardUserCompanyInfoDAO cardUserCompanyInfoDAO;

    @Autowired
    private CardBaseInfoDAO cardBaseInfoDAO;

    @Autowired
    private CardSettingDAO cardSettingDAO;

    @Autowired
    private MaterialDAO materialDAO;

    @Autowired
    private TemplateDAO templateDAO;

    @Autowired
    private EnterpriseDAO enterpriseDAO;

    @Autowired
    private WxappDAO wxappDAO;

    @Autowired
    private ComponentCufaceMaterialConfigComponentDAO componentCufaceMaterialConfigComponentDAO;

    @Autowired
    private CardConnectUserInfoDAO cardConnectUserInfoDAO;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ContentCheckManager contentCheckManager;

    @Autowired
    private TextCheckService textCheckService;

    @Autowired
    private ContentCheckService contentCheckService;

    @Override
    public CardFullDTO getCardFullDTO(CardDTO cardDTO) {
        Context context = new Context(cardFullStrategy);
        return context.contextInterface(cardDTO);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean addPersonalCard(IndustryDTO industryDTO) {
        // 插入user表
        UserDO userDO = new UserDO();
        userDO.setEnterpriseId(0L);
        userDO.setMemberId(industryDTO.getMemberId());
        userDO.setIndustryId(industryDTO.getId());
        userDO.setStatus(UserStatusEnum.AUDITED.getValue());
        userDO.setCheckStatus(UserCheckStatusEnum.NORMAL.getValue());
        userDO.setCheckRemark("");
        userDO.setLastLoginAt(DateTimeUtils.getNowTime());
        userDO.setVerifytime(DateTimeUtils.getNowTime());
        Long userId = userDAO.insertSelective(userDO);
        if (userId == null || userId <= 0) {
            return false;
        }

        //生成card_user_info card_user_company_info company card_base_info address
        AddressDO addressDO = new AddressDO();
        addressDO.setUserId(userId);
        addressDO.setAddressZh("xx市xx区xx号");
        addressDO.setAddressEn("No.xx,xx district,xx city");
        Long addressId = addressDAO.insertSelective(addressDO);

        MemberDO memberDO = memberDAO.selectById(industryDTO.getMemberId());
        CardUserInfoDO cardUserInfoDO = new CardUserInfoDO();
        cardUserInfoDO.setUserId(userId);
        cardUserInfoDO.setName(memberDO.getNickname());
        cardUserInfoDO.setNameEn(memberDO.getNickname());
        cardUserInfoDO.setMobile(memberDO.getMobile());
        cardUserInfoDO.setAddressId(addressId);
        Long cardUserInfoId = cardUserInfoDAO.insertSelective(cardUserInfoDO);

        CompanyDO companyDO = new CompanyDO();
        companyDO.setName("xxx有限公司");
        companyDO.setNameEn("xxxxxx Co., Ltd");
        Long companyId = companyDAO.insertSelective(companyDO);

        CardUserCompanyInfoDO cardUserCompanyInfoDO = new CardUserCompanyInfoDO();
        cardUserCompanyInfoDO.setCardUserInfoId(cardUserInfoId);
        cardUserCompanyInfoDO.setCompanyId(companyId);
        cardUserCompanyInfoDO.setDepartment("xxx部");
        cardUserCompanyInfoDO.setJob("首席xxx官");
        cardUserCompanyInfoDO.setDepartmentEn("xxxx Department");
        cardUserCompanyInfoDO.setJobEn("Chief xxxx Officer");
        cardUserCompanyInfoDAO.insertSelective(cardUserCompanyInfoDO);

        CardBaseInfoDO cardBaseInfoDO = new CardBaseInfoDO();
        cardBaseInfoDO.setUserId(userId);
        cardBaseInfoDO.setTemplateId(1L);
        Long cardBaseInfoId = cardBaseInfoDAO.insertSelective(cardBaseInfoDO);

        // 插入card表
        CardDO cardDO = new CardDO();
        cardDO.setEnterpriseId(0L);

        cardDO.setUserId(userId);
        cardDO.setBaseInfoId(cardBaseInfoId);
        cardDO.setUserInfoId(cardUserInfoId);
        Long insert = cardDAO.insertSelective(cardDO);
        return insert > 0;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean cardZh(CardParamRequest cardParamRequest) {
        //新增敏感词审核
        checkPersonalUserInfo(cardParamRequest,cardParamRequest.getMemberId(),SourceTypeEnum.APPLET.getValue());
        // 修改 card_user_info
        // 根据memberId查询userId
        UserDO userDO = userDAO.selectById(cardParamRequest.getUserId());
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(userDO.getId());
        cardUserInfoDO.setName(cardParamRequest.getName());
        cardUserInfoDO.setMobile(cardParamRequest.getMobile());
        cardUserInfoDO.setWechat(cardParamRequest.getWechat());
        cardUserInfoDO.setEmail(cardParamRequest.getEmail());
        cardUserInfoDO.setZhIsUpdated(1);
        Boolean flag = cardUserInfoDAO.updateSelective(cardUserInfoDO);
        // 修改公司信息
        updateCardUserCompanyInfo(cardParamRequest,cardUserInfoDO.getId());
        //修改地址
        updateAddress(cardUserInfoDO, cardParamRequest);
        // 修改微信头像
        MemberDO memberDO = memberDAO.selectById(cardParamRequest.getMemberId());
        //头像进行图片检测
        if (StringUtils.isNotEmpty(cardParamRequest.getAvatar())) {
            MemberDO avatarResult = checkAvatar(cardParamRequest.getAvatar(),userDO.getId());
            memberDO.setNeedReview(avatarResult.getNeedReview());
            memberDO.setCheckResult(avatarResult.getCheckResult());
        }
        memberDO.setAvatarLocal(cardParamRequest.getAvatar());
        memberDAO.updateSelective(memberDO);
        return flag;
    }

    public MemberDO checkAvatar(String avatar,Long userId) {
        MemberDO memberDO = new MemberDO();
        memberDO.setNeedReview(0);
        CheckResultDTO checkResultDTO = contentCheckService.singleImageCheck(avatar,userId);
        if (checkResultDTO == null) {
            throw new BusinessErrorException(BusinessCode.IMAGE_CHECK_ERROR);
        }
        CheckImageDTO checkImageDTO = new CheckImageDTO();
        if (checkResultDTO.getAd().equals("block") || checkResultDTO.getPorn().equals("block") || checkResultDTO.getTerrorism().equals("block")) {
            AliyunUitls.deleteSingleFile(BucketTypeEnum.IMAGE.getValue(),avatar);
            throw new BusinessErrorException(BusinessCode.IMAGE_CONTAIN_SENSITIVE_INFO);
        } else {
            if (checkResultDTO.getAd().equals("review") || checkResultDTO.getPorn().equals("review") || checkResultDTO.getTerrorism().equals("review")) {
                memberDO.setNeedReview(1);
            }
            checkImageDTO.setCheckResult(JSONObject.toJSONString(checkResultDTO));
            memberDO.setCheckResult(JSONObject.toJSONString(checkResultDTO));
        }
        return memberDO;
    }

    public void checkPersonalUserInfo(CardParamRequest cardParamRequest,Long memberId,Integer sourceId) {
        TextCheckRequest request = new TextCheckRequest();
        request.setUserId(cardParamRequest.getUserId());
        request.setName(cardParamRequest.getName());
        request.setAddress(cardParamRequest.getAddressZh());

        List<CardUserCompanyInfoDTO> companyInfos = cardParamRequest.getCompanyInfos();
        if(CollectionUtils.isNotEmpty(companyInfos)) {
            for (int i = 0; i < companyInfos.size(); i++) {
                if (i == 0) {
                    request.setCompany(companyInfos.get(i).getName());
                    request.setDepartment(companyInfos.get(i).getDepartment());
                    request.setJob(companyInfos.get(i).getJob());
                } else {
                    request.setOtherCompany(companyInfos.get(i).getName());
                    request.setOtherDepartment(companyInfos.get(i).getDepartment());
                    request.setOtherJob(companyInfos.get(i).getJob());
                }
            }
        }

        textCheckService.textCheck(request,memberId,sourceId);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean cardEn(CardParamRequest cardParamRequest) {
        // 修改 card_user_info
        UserDO userDO = userDAO.selectById(cardParamRequest.getUserId());
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(userDO.getId());
        cardUserInfoDO.setNameEn(cardParamRequest.getNameEn());
        cardUserInfoDO.setMobile(cardParamRequest.getMobile());
        cardUserInfoDO.setWechat(cardParamRequest.getWechat());
        cardUserInfoDO.setEmail(cardParamRequest.getEmail());
        cardUserInfoDO.setEnIsUpdated(1);
        Boolean flag = cardUserInfoDAO.updateSelective(cardUserInfoDO);
        // 修改 card_user_company_info
        updateCardUserCompanyInfo(cardParamRequest, cardUserInfoDO.getId());
        // 修改地址
        updateAddress(cardUserInfoDO, cardParamRequest);
        // 修改微信头像
        MemberDO memberDO = memberDAO.selectById(cardParamRequest.getMemberId());
        memberDO.setAvatarLocal(cardParamRequest.getAvatar());
        memberDAO.updateSelective(memberDO);
        return flag;
    }

    /**
     * 修改 card_user_company_info
     * @param cardParamRequest
     * @param cardUserInfoId
     */
    private void updateCardUserCompanyInfo(CardParamRequest cardParamRequest, Long cardUserInfoId) {
        // 修改 card_user_company_info
        List<CardUserCompanyInfoDTO> companyInfos = cardParamRequest.getCompanyInfos();
        if(CollectionUtils.isNotEmpty(companyInfos)) {
            companyInfos.stream().forEach(companyInfo -> {
                Long companyId = null;
                if (companyInfo.getCompanyId() > 0) {
                    CompanyDO companyDO = companyDAO.selectById(companyInfo.getCompanyId());
                    if (StringUtils.isNotEmpty(companyInfo.getName())) {
                        companyDO.setName(companyInfo.getName());
                    }
                    companyDAO.updateSelective(companyDO);
                    companyId = companyDO.getId();
                } else {
                    CompanyDO companyDO =  new CompanyDO();
                    companyDO.setName(companyInfo.getName() == null ? "" : companyInfo.getName());
                    companyDO.setNameEn(companyInfo.getNameEn() == null ? "" : companyInfo.getNameEn());
                    companyId = companyDAO.insertSelective(companyDO);
                }
                if (companyInfo.getId() > 0) {
                    CardUserCompanyInfoDO cardUserCompanyInfoDO = cardUserCompanyInfoDAO.selectById(companyInfo.getId());
                    if (StringUtils.isNotEmpty(companyInfo.getJob())) {
                        cardUserCompanyInfoDO.setJob(companyInfo.getJob());
                    }
                    if (StringUtils.isNotEmpty(companyInfo.getDepartment())) {
                        cardUserCompanyInfoDO.setDepartment(companyInfo.getDepartment());
                    }
                    cardUserCompanyInfoDO.setCompanyId(companyId);
                    cardUserCompanyInfoDAO.updateSelective(cardUserCompanyInfoDO);
                } else {
                    CardUserCompanyInfoDO cardUserCompanyInfoDO = new CardUserCompanyInfoDO();
                    cardUserCompanyInfoDO.setCardUserInfoId(cardUserInfoId);
                    cardUserCompanyInfoDO.setJob(companyInfo.getJob() == null ? "" : companyInfo.getJob());
                    cardUserCompanyInfoDO.setDepartment(companyInfo.getDepartment() == null ? "" : companyInfo.getDepartment());
                    cardUserCompanyInfoDO.setJobEn(companyInfo.getJobEn() == null ? "" : companyInfo.getJobEn());
                    cardUserCompanyInfoDO.setDepartmentEn(companyInfo.getDepartmentEn() == null ? "" : companyInfo.getDepartmentEn());
                    cardUserCompanyInfoDO.setCompanyId(companyId);
                    cardUserCompanyInfoDAO.insert(cardUserCompanyInfoDO);
                }
            });
        }
    }

    @Override
    public Boolean deleteUserCompanyInfo (Long cardUserCompanyInfoId,Long userId) {
        UserDO userDO = userDAO.selectById(userId);
        CardUserCompanyInfoDO cardUserCompanyInfoDO = cardUserCompanyInfoDAO.selectById(cardUserCompanyInfoId);
        if (cardUserCompanyInfoDO != null) {
            if (userDO.getEnterpriseId() ==0) {
                //个人名片要清空company表
                //判断该公司ID是否还有使用
                CardUserCompanyInfoDO cardUserCompanyInfoDO1 = cardUserCompanyInfoDAO.selectByIdAndCompanyId(cardUserCompanyInfoId,cardUserCompanyInfoDO.getCompanyId());
                if (cardUserCompanyInfoDO1 == null) {
                    companyDAO.deleteCompany(cardUserCompanyInfoDO.getCompanyId());
                }
            }
            cardUserCompanyInfoDAO.deleteById(cardUserCompanyInfoDO.getId());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = BusinessErrorException.class)
    public Boolean editCard(CardEditRequest cardEditRequest, Long adminId) {
        TextCheckRequest request = new TextCheckRequest();
        request.setName(cardEditRequest.getNameZh());

        // 修改名片用户信息
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectById(cardEditRequest.getId());
        cardUserInfoDO.setName(cardEditRequest.getNameZh());
        cardUserInfoDO.setAddressId(cardEditRequest.getAddressId());
        Boolean aBoolean = cardUserInfoDAO.updateSelective(cardUserInfoDO);
        request.setUserId(cardUserInfoDO.getUserId());
        // 修改公司信息
        List<CardEditDetailRequest> cardEditDetailRequests = cardEditRequest.getCardEditDetailRequests();
        if (cardEditDetailRequests.size() > 0) {
            for(int i = 0;i < cardEditDetailRequests.size();i++) {
                //先修改公司名
                CompanyDO companyDO = companyDAO.selectById(cardEditDetailRequests.get(i).getCompanyId());
                companyDO.setName(cardEditDetailRequests.get(i).getCompanyZh());
                companyDAO.updateSelective(companyDO);

                //修改部门、职位
                CardUserCompanyInfoDO cardUserCompanyInfoDO = cardUserCompanyInfoDAO.selectById(cardEditDetailRequests.get(i).getId());
                cardUserCompanyInfoDO.setDepartment(cardEditDetailRequests.get(i).getDepartmentName());
                cardUserCompanyInfoDO.setJob(cardEditDetailRequests.get(i).getJobName());
                cardUserCompanyInfoDAO.updateSelective(cardUserCompanyInfoDO);

                if (i == 0) {
                    request.setCompany(cardEditDetailRequests.get(i).getCompanyZh());
                    request.setDepartment(cardEditDetailRequests.get(i).getDepartmentName());
                    request.setJob(cardEditDetailRequests.get(i).getJobName());
                } else {
                    request.setOtherCompany(cardEditDetailRequests.get(i).getCompanyZh());
                    request.setOtherDepartment(cardEditDetailRequests.get(i).getDepartmentName());
                    request.setOtherJob(cardEditDetailRequests.get(i).getJobName());
                }
            }
        }

        if (cardEditRequest.getForwardTitle() != null) {
            request.setVisitorTitle(cardEditRequest.getVisitorTitle());
            request.setForwardTitle(cardEditRequest.getForwardTitle());
            CardSettingDO cardSettingDO = cardSettingDAO.selectByUserId(cardUserInfoDO.getUserId());
            if (cardSettingDO != null) {
                cardSettingDO.setForwardTitle(cardEditRequest.getForwardTitle());
                cardSettingDO.setVisitorTitle(cardEditRequest.getVisitorTitle());
                cardSettingDAO.updateSelective(cardSettingDO);
            } else {
                cardSettingDO = new CardSettingDO();
                cardSettingDO.setForwardTitle(cardEditRequest.getForwardTitle());
                cardSettingDO.setVisitorTitle(cardEditRequest.getVisitorTitle());
                cardSettingDO.setUserId(cardUserInfoDO.getUserId());
                cardSettingDAO.insertSelective(cardSettingDO);
            }
        }
        textCheckService.textCheck(request,adminId,SourceTypeEnum.OPERATE_BACKEND.getValue());
        return aBoolean;
    }

    @Override
    public CardMaterialResponse cardMaterialDetailNew(Long cardId) {
        CardMaterialResponse cardMaterialResponse = new CardMaterialResponse();
        // 查询老的模板素材列表
        List<CardMaterialDetailDTO> resultDTO = new ArrayList<>();
        CardDO cardDO = cardDAO.selectById(cardId);
        if (cardDO == null || cardDO.getIsDelete().equals(DeleteEnum.YES.getValue())) {
            throw new BusinessErrorException(BusinessCode.CARD_NOT_EXIST);
        }
        //用户信息
        CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectById(cardDO.getBaseInfoId());
        if (cardBaseInfoDO == null || cardBaseInfoDO.getIsDelete() == 1) {
            throw new BusinessErrorException(BusinessCode.CARD_NOT_EXIST);
        }
        String[] materialIds = cardBaseInfoDO.getMaterialIds().split(",");
        List<Long> materialIdList = new ArrayList<>();
        for (String materialId : materialIds) {
            materialIdList.add(Long.valueOf(materialId));
        }
        // 如果是老的模板组件
        TemplateDO templateDO = templateDAO.selectById(cardBaseInfoDO.getTemplateId());
        if(null != templateDO) {
            List<String> partList = JSON.parseArray(templateDO.getContent(),String.class);
            //定义一个map
            Map<String ,List<Integer>> map = new HashMap<>();
            map.put(SystemConstants.MAP_EKY_CARD, Arrays.asList(MaterialTypeEnum.CARD_BACKGROUND_VEDIO.getValue(),
                    MaterialTypeEnum.PICTURE.getValue(),MaterialTypeEnum.LOGO.getValue()));
            map.put(SystemConstants.MAP_EKY_VIDEO, Arrays.asList(MaterialTypeEnum.ENTERPRISE_PROPAGATE_VEDIO.getValue(),
                    MaterialTypeEnum.PROPAGATE_VEDIO_BACKGROUND_PICATURE.getValue()));
            map.put(SystemConstants.MAP_EKY_IMAGE, Arrays.asList(MaterialTypeEnum.LONG_PICTURE.getValue()));
            map.put(SystemConstants.MAP_EKY_VERTICAL_VIDEO, Arrays.asList(MaterialTypeEnum.LOGO.getValue(), MaterialTypeEnum.ENDWAYS_VEDIO.getValue()));
            map.put(SystemConstants.MAP_EKY_HORIZONTAL_VIDEO,Arrays.asList(MaterialTypeEnum.HORIZONTAL_PICTURE.getValue()));
            for (String part : partList) {
                List<Integer> typeList = map.get(part);
                List<MaterialDO> materialDOList = materialDAO.selectByMaterialIdAndType(materialIdList,typeList);
                List<CardMaterialDetailDTO.MaterialBean> materialBeans = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(materialDOList)) {
                    DataConvertUtils.convertDOList2DTOList(materialDOList, materialBeans, CardMaterialDetailDTO.MaterialBean.class);
                }
                CardMaterialDetailDTO enterpriseCardMaterialDetailDTO = new CardMaterialDetailDTO();
                enterpriseCardMaterialDetailDTO.setPart(part);
                enterpriseCardMaterialDetailDTO.setMaterial(materialBeans);
                resultDTO.add(enterpriseCardMaterialDetailDTO);
            }
        }

        // 兼容组件的数据
        List<Long> componentIds = Arrays.asList(cardBaseInfoDO.getComponentId());
        List<ComponentCufaceMaterialConfigComponentDTO> componentDTOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(componentIds)) {
            List<ComponentCufaceMaterialConfigComponentDO> componentDOS = componentCufaceMaterialConfigComponentDAO.selectByComponentIds(componentIds);
            // DO 转 DTO
            if(CollectionUtils.isNotEmpty(componentDOS)) {
                DataConvertUtils.convertDOList2DTOList(componentDOS, componentDTOS, ComponentCufaceMaterialConfigComponentDTO.class);
            }
        }
        // 构建返回数据
        if(CollectionUtils.isNotEmpty(resultDTO)) {
            cardMaterialResponse.setMaterialType(MaterialResponseTypeEnum.MATERIAL.getValue());
            cardMaterialResponse.setCardMaterialDetailDTOS(resultDTO);
        }
        if(CollectionUtils.isNotEmpty(componentDTOS)) {
            cardMaterialResponse.setMaterialType(MaterialResponseTypeEnum.COMPONENT.getValue());
            cardMaterialResponse.setCufaceMaterialConfigComponentDTO(componentDTOS.get(0));
        }
//        if(CollectionUtils.isNotEmpty(materialIdList) && !"0".equals(materialIds[0]) && CollectionUtils.isNotEmpty(componentIds)) {
//            throw new BusinessErrorException(BusinessCode.CARD_MATERIAL_NOT_EXSIT);
//        }
        return cardMaterialResponse;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean editEnterpriseCard(EnterpriseCardRequest enterpriseCardRequest) {
        log.info("CardManager.editEnterpriseCard 修改企业名片 : {}", JSON.toJSONString(enterpriseCardRequest));
        // 查询cardDO
        CardDO cardDO = cardDAO.selectById(enterpriseCardRequest.getId());
        // 构建cardBaseInfo
        CardBaseInfoDO cardBaseInfoDO = new CardBaseInfoDO();
        cardBaseInfoDO.setId(cardDO.getBaseInfoId());
        cardBaseInfoDO.setEnterpriseId(enterpriseCardRequest.getEnterpriseId());
        cardBaseInfoDO.setTemplateId(enterpriseCardRequest.getTemplateId());
        cardBaseInfoDO.setMaterialIds(String.join(",", enterpriseCardRequest.getMaterialIds().
                stream().map(String::valueOf).collect(Collectors.toList())));
        // TODO 设置ComponentId
        Boolean flag1 = cardBaseInfoDAO.updateSelective(cardBaseInfoDO);
        log.info("CardManager.editEnterpriseCard 修改企业名片基础信息结果 : {}", flag1);
        // 构建cardDO
        cardDO.setTitle(enterpriseCardRequest.getTitle());
        cardDO.setEnterpriseId(enterpriseCardRequest.getEnterpriseId());
        cardDO.setTitle(enterpriseCardRequest.getTitle());
        cardDO.setBaseInfoId(cardDO.getBaseInfoId());
        Boolean flag2 = cardDAO.updateSelective(cardDO);
        log.info("CardManager.editEnterpriseCard 修改企业名片信息结果 : {}", flag2);
        return flag2;
    }

    @Override
    public EnterpriseCardDetailResponse enterpriseCardDetail(EnterpriseCardRequest enterpriseCardRequest) {
        EnterpriseCardDetailResponse enterpriseCardDetailResponse = new EnterpriseCardDetailResponse();
        log.info("CardManager.enterpriseCardDetail 名片详情请求参数 : {}", enterpriseCardRequest);
        // 查询CardDO
        CardDO cardDO = cardDAO.selectById(enterpriseCardRequest.getId());
        // 查询BaseInfoDO
        CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectById(cardDO.getBaseInfoId());

        // DO 转 DTO
        CardBaseInfoDTO cardBaseInfoDTO = DataConvertUtils.convertDO2DTO(cardBaseInfoDO, CardBaseInfoDTO.class);
        enterpriseCardDetailResponse.setCardBaseInfoDTO(cardBaseInfoDTO);
        CardDTO cardDTO = DataConvertUtils.convertDO2DTO(cardDO, CardDTO.class);
        enterpriseCardDetailResponse.setCardDTO(cardDTO);
        enterpriseCardDetailResponse.getCardBaseInfoDTO().setMaterialIds(cardBaseInfoDO.getMaterialIds());

        // 查询素材list
        if(StringUtils.isNotEmpty(cardBaseInfoDO.getMaterialIds()) && !"0".equals(cardBaseInfoDO.getMaterialIds())) {
            List<MaterialDO> materialDOS = materialDAO.selectByMaterialIdList(Arrays.stream(cardBaseInfoDO.getMaterialIds().split(","))
                    .map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
            List<MaterialDTO> materialDTOS = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(materialDOS)) {
                DataConvertUtils.convertDOList2DTOList(materialDOS, materialDTOS, MaterialDTO.class);
                enterpriseCardDetailResponse.getCardBaseInfoDTO().setMaterialDTOS(materialDTOS);
            }
        }
        return enterpriseCardDetailResponse;
    }

    @Override
    public FavoriteCardDTO cardConnectInfo(Long userId, Long oldPersonalUserId, Long oldEnterpriseUserId) {
        //id参数兼容老版本
        if (userId == null || userId == 0) {
            if (oldPersonalUserId != null && oldPersonalUserId != 0) {
                userId = userDAO.selectPersonalUserIdByOldId(oldPersonalUserId);
            } else if (oldEnterpriseUserId != null && oldEnterpriseUserId != 0) {
                userId = userDAO.selectEnterpriserUserIdByOldId(oldEnterpriseUserId);
            }
        }

        //获取绑定的用户
        CardConnectUserInfoDO cardConnectUserInfoDO = cardConnectUserInfoDAO.selectByDeletedUserId(userId);
        if (cardConnectUserInfoDO == null) {
            return null;
        }

        FavoriteCardDTO favoriteCardDTO = new FavoriteCardDTO();
        favoriteCardDTO.setUserId(cardConnectUserInfoDO.getConnectUserId());
        favoriteCardDTO.setCardId(cardConnectUserInfoDO.getConnectCardId());

        UserDO userDO = userDAO.selectById(cardConnectUserInfoDO.getConnectUserId());
        favoriteCardDTO.setEnterpriseId(userDO.getEnterpriseId());

        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(cardConnectUserInfoDO.getConnectUserId());
        favoriteCardDTO.setMobile(cardUserInfoDO.getMobile());
        favoriteCardDTO.setName(cardUserInfoDO.getName());
        favoriteCardDTO.setFontColor(cardUserInfoDO.getFontColor());
        List<Long> cardUserInfoIds = Arrays.asList(cardUserInfoDO.getId());
        List<CardUserCompanyInfoDO> companyInfos = cardUserCompanyInfoDAO.selectByCardUserInfoIds(cardUserInfoIds);
        CompanyDO companyDO = companyDAO.selectById(companyInfos.get(0).getCompanyId());
        if(null != companyDO) {
            favoriteCardDTO.setCompany(companyDO.getName());
        }
        favoriteCardDTO.setDepartment(companyInfos.get(0).getDepartment());
        favoriteCardDTO.setJob(companyInfos.get(0).getJob());

        MemberDO memberDO = memberDAO.selectById(userDO.getMemberId());
        if (memberDO != null) {
            favoriteCardDTO.setAvatar(memberDO.getAvatarLocal());
        } else {
            favoriteCardDTO.setAvatar("");
        }

        favoriteCardDTO.setFilePath("");

        CardDO cardDO = cardDAO.selectById(cardConnectUserInfoDO.getConnectCardId());
        CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectById(cardDO.getBaseInfoId());
        //获取封面图
        if (cardBaseInfoDO != null && !cardBaseInfoDO.getMaterialIds().equals("")) {
            String[] materialIds = cardBaseInfoDO.getMaterialIds().split(",");
            List<Long> materialIdList = new ArrayList<>();
            for(String materialId : materialIds) {
                materialIdList.add(Long.valueOf(materialId));
            }
            if (materialIds.length > 0) {
                List<MaterialDO> materialDOList = materialDAO.selectByMaterialIdList(materialIdList);
                if (materialDOList != null && materialDOList.size() > 0) {
                    List<Long> typeList = Arrays.asList(1L,2L,4L,5L);
                    for (MaterialDO materialDO : materialDOList) {
                        if (typeList.contains(cardBaseInfoDO.getTemplateId())) {
                            if (materialDO.getType() == 1 || materialDO.getType() == 2) {
                                favoriteCardDTO.setFilePath(materialDO.getFilePath());
                            }
                        } else {
                            if (materialDO.getType() == 6) {
                                favoriteCardDTO.setFilePath(materialDO.getFilePath());
                            }
                        }
                    }
                }
            }
        }
        return favoriteCardDTO;
    }

    /**
     * 修改地址信息
     * @param cardUserInfoDO
     * @param cardParamRequest
     */
    private void updateAddress(CardUserInfoDO cardUserInfoDO, CardParamRequest cardParamRequest) {
        //修改地址
        AddressDO addressDO = addressDAO.selectById(cardUserInfoDO.getAddressId());
        addressDO.setAddressZh(cardParamRequest.getAddressZh());
        addressDO.setAddressEn(cardParamRequest.getAddressEn());
        addressDO.setLongitude(cardParamRequest.getLongitude());
        addressDO.setLatitude(cardParamRequest.getLatitude());
        addressDAO.updateSelective(addressDO);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Long addCardEnterprise(EnterpriseCardAddParam enterpriseCardAddParam) {
        com.sright.bcard.common.service.share.dto.enterprise.EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseDTO(enterpriseCardAddParam.getEnterpriseId());
        List<UserDO> userDOS = userDAO.selectByEnterpriseId(enterpriseCardAddParam.getEnterpriseId());
        if(CollectionUtils.isNotEmpty(userDOS) && userDOS.size() >= enterpriseDTO.getCardNum() ) {
            throw new BusinessErrorException(BusinessCode.ENTERPRISE_STAFF_LIMIT);
        }
        // 不添加card_base_info表，因为目前需求企业用户所有展示名片全都由企业后台设置，小程序端除编辑个人信息外其他都不能编辑
        // 添加user表
        UserDO userDO = new UserDO();
        userDO.setEnterpriseId(enterpriseCardAddParam.getEnterpriseId());
        userDO.setMemberId(enterpriseCardAddParam.getMemberId());
        userDO.setStatus(1);
        Long userId = userDAO.insertSelective(userDO);

        // 添加card_user_info表
        CardUserInfoDO cardUserInfoDO = new CardUserInfoDO();
        cardUserInfoDO.setUserId(userId);
        cardUserInfoDO.setName(enterpriseCardAddParam.getName());
        cardUserInfoDO.setMobile(enterpriseCardAddParam.getMobile());
        cardUserInfoDO.setWechat(enterpriseCardAddParam.getWechat());
        cardUserInfoDO.setEmail(enterpriseCardAddParam.getEmail());
        cardUserInfoDO.setAddressId(enterpriseCardAddParam.getAddressId());
        Long cardUserInfoId = cardUserInfoDAO.insertSelective(cardUserInfoDO);

        TextCheckRequest request = new TextCheckRequest();
        request.setUserId(userId);
        request.setName(enterpriseCardAddParam.getName());

        // 添加card_user_company_info表
        List<CardUserCompanyInfoDTO> cardUserCompanyInfoDTOList = enterpriseCardAddParam.getCompanyInfos();
        if (CollectionUtils.isNotEmpty(cardUserCompanyInfoDTOList)) {
            for (int i = 0; i < cardUserCompanyInfoDTOList.size(); i++) {
                if (i == 0) {
                    request.setDepartment(cardUserCompanyInfoDTOList.get(i).getDepartment());
                    request.setJob(cardUserCompanyInfoDTOList.get(i).getJob());
                } else {
                    request.setOtherDepartment(cardUserCompanyInfoDTOList.get(i).getDepartment());
                    request.setOtherJob(cardUserCompanyInfoDTOList.get(i).getJob());
                }

                CardUserCompanyInfoDO cardUserCompanyInfoDO = new CardUserCompanyInfoDO();
                cardUserCompanyInfoDO.setCompanyId(cardUserCompanyInfoDTOList.get(i).getCompanyId());
                cardUserCompanyInfoDO.setJob(cardUserCompanyInfoDTOList.get(i).getJob());
                cardUserCompanyInfoDO.setJobEn(cardUserCompanyInfoDTOList.get(i).getJobEn());
                cardUserCompanyInfoDO.setDepartment(cardUserCompanyInfoDTOList.get(i).getDepartment());
                cardUserCompanyInfoDO.setDepartmentEn(cardUserCompanyInfoDTOList.get(i).getDepartmentEn());
                cardUserCompanyInfoDO.setCardUserInfoId(cardUserInfoId);
                cardUserCompanyInfoDAO.insertSelective(cardUserCompanyInfoDO);
            }
        }
        textCheckService.textCheck(request,enterpriseCardAddParam.getMemberId(),SourceTypeEnum.APPLET.getValue());
        return userId;
    }

    private void updateEnterpriseCardUserCompanyInfo(EnterpriseCardAddParam enterpriseCardAddParam, Long cardUserInfoId) {
        // 修改 card_user_company_info
        List<CardUserCompanyInfoDTO> companyInfos = enterpriseCardAddParam.getCompanyInfos();
        if(CollectionUtils.isNotEmpty(companyInfos)) {
            companyInfos.stream().forEach(companyInfo -> {
                Long companyId = null;
                if (companyInfo.getCompanyId() > 0) {
                    CompanyDO companyDO = companyDAO.selectById(companyInfo.getCompanyId());
                    if (StringUtils.isNotEmpty(companyInfo.getName())) {
                        companyDO.setName(companyInfo.getName());
                    }
                    if (StringUtils.isNotEmpty(companyInfo.getName())) {
                        companyDO.setNameEn(companyInfo.getNameEn());
                    }
                    companyDAO.updateSelective(companyDO);
                    companyId = companyDO.getId();
                } else {
                    CompanyDO companyDO =  new CompanyDO();
                    companyDO.setName(companyInfo.getName() == null ? "" : companyInfo.getName());
                    companyDO.setNameEn(companyInfo.getNameEn() == null ? "" : companyInfo.getNameEn());
                    companyId = companyDAO.insertSelective(companyDO);
                }
                if (companyInfo.getId() > 0) {
                    CardUserCompanyInfoDO cardUserCompanyInfoDO = cardUserCompanyInfoDAO.selectById(companyInfo.getId());
                    if (StringUtils.isNotEmpty(companyInfo.getJob())) {
                        cardUserCompanyInfoDO.setJob(companyInfo.getJob());
                    }
                    if (StringUtils.isNotEmpty(companyInfo.getJobEn())) {
                        cardUserCompanyInfoDO.setJobEn(companyInfo.getJobEn());
                    }
                    if (StringUtils.isNotEmpty(companyInfo.getDepartment())) {
                        cardUserCompanyInfoDO.setDepartment(companyInfo.getDepartment());
                    }
                    if (StringUtils.isNotEmpty(companyInfo.getDepartmentEn())) {
                        cardUserCompanyInfoDO.setDepartmentEn(companyInfo.getDepartmentEn());
                    }
                    cardUserCompanyInfoDO.setCompanyId(companyId);
                    cardUserCompanyInfoDAO.updateSelective(cardUserCompanyInfoDO);
                } else {
                    CardUserCompanyInfoDO cardUserCompanyInfoDO = new CardUserCompanyInfoDO();
                    cardUserCompanyInfoDO.setCardUserInfoId(cardUserInfoId);
                    cardUserCompanyInfoDO.setJob(companyInfo.getJob() == null ? "" : companyInfo.getJob());
                    cardUserCompanyInfoDO.setDepartment(companyInfo.getDepartment() == null ? "" : companyInfo.getDepartment());
                    cardUserCompanyInfoDO.setJobEn(companyInfo.getJobEn() == null ? "" : companyInfo.getJobEn());
                    cardUserCompanyInfoDO.setDepartmentEn(companyInfo.getDepartmentEn() == null ? "" : companyInfo.getDepartmentEn());
                    cardUserCompanyInfoDO.setCompanyId(companyId);
                    cardUserCompanyInfoDAO.insert(cardUserCompanyInfoDO);
                }
            });
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean editCardEnterpriseZh(EnterpriseCardAddParam enterpriseCardAddParam) {
        checkEnterpriseUserInfo(enterpriseCardAddParam,enterpriseCardAddParam.getMemberId());
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(enterpriseCardAddParam.getUserId());
        cardUserInfoDO.setName(enterpriseCardAddParam.getName());
        cardUserInfoDO.setMobile(enterpriseCardAddParam.getMobile());
        cardUserInfoDO.setWechat(enterpriseCardAddParam.getWechat());
        cardUserInfoDO.setEmail(enterpriseCardAddParam.getEmail());
        cardUserInfoDO.setAddressId(enterpriseCardAddParam.getAddressId());
        cardUserInfoDO.setZhIsUpdated(1);
        Boolean flag = cardUserInfoDAO.updateSelective(cardUserInfoDO);

        // 修改 card_user_company_info
        updateEnterpriseCardUserCompanyInfo(enterpriseCardAddParam,cardUserInfoDO.getId());
        // 修改头像
        MemberDO memberDO = memberDAO.selectById(enterpriseCardAddParam.getMemberId());
        //头像进行图片检测
        if (StringUtils.isNotEmpty(enterpriseCardAddParam.getAvatar())) {
            MemberDO avatarResult = checkAvatar(enterpriseCardAddParam.getAvatar(),enterpriseCardAddParam.getUserId());
            memberDO.setNeedReview(avatarResult.getNeedReview());
            memberDO.setCheckResult(avatarResult.getCheckResult());
        }
        memberDO.setAvatarLocal(enterpriseCardAddParam.getAvatar());
        memberDAO.updateSelective(memberDO);
        return flag;
    }

    public void checkEnterpriseUserInfo(EnterpriseCardAddParam enterpriseCardAddParam,Long memberId) {
        TextCheckRequest request = new TextCheckRequest();
        request.setUserId(enterpriseCardAddParam.getUserId());
        request.setName(enterpriseCardAddParam.getName());

        List<CardUserCompanyInfoDTO> companyInfos = enterpriseCardAddParam.getCompanyInfos();
        if(CollectionUtils.isNotEmpty(companyInfos)) {
            for (int i = 0; i < companyInfos.size(); i++) {
                if (i == 0) {
                    request.setDepartment(companyInfos.get(i).getDepartment());
                    request.setJob(companyInfos.get(i).getJob());
                } else {
                    request.setOtherDepartment(companyInfos.get(i).getDepartment());
                    request.setOtherJob(companyInfos.get(i).getJob());
                }
            }
        }

        textCheckService.textCheck(request,memberId,SourceTypeEnum.APPLET.getValue());
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Long editCardEnterprise(CardSaveParam cardSaveParam) {
        // 修改card表
        CardDO cardDO = new CardDO();
        cardDO.setEnterpriseId(cardSaveParam.getEnterpriseId());
        cardDO.setUserId(0L);
        cardDAO.updateAll(cardDO);
        // 修改card_base_info表
        CardBaseInfoDO cardBaseInfoDO = new CardBaseInfoDO();
        cardBaseInfoDO.setUserId(0L);
        cardBaseInfoDO.setEnterpriseId(cardSaveParam.getEnterpriseId());
        cardBaseInfoDAO.updateAll(cardBaseInfoDO);
        // 修改card_setting表
        CardSettingDO cardSettingDO = new CardSettingDO();
        cardSettingDO.setEnterpriseId(cardSaveParam.getEnterpriseId());
        cardSettingDO.setUserId(0L);
        cardSettingDAO.updateAll(cardSettingDO);
        // 修改card_user_info表
        CardUserInfoDO cardUserInfoDO = new CardUserInfoDO();
        cardUserInfoDO.setAddressId(cardSaveParam.getAddressId());
        cardUserInfoDO.setEmail(cardSaveParam.getEmail());
        cardUserInfoDO.setMobile(cardSaveParam.getMobile());
        cardUserInfoDO.setName(cardSaveParam.getName());
        cardUserInfoDO.setNameEn(cardSaveParam.getNameEn());
        cardUserInfoDO.setUserId(0L);
        cardUserInfoDO.setWechat(cardSaveParam.getWechat());
        cardUserInfoDAO.updateAll(cardUserInfoDO);
        // 修改card_user_company_info表
        CardUserCompanyInfoDO cardUserCompanyInfoDO = new CardUserCompanyInfoDO();
        cardUserCompanyInfoDO.setCompanyId(cardSaveParam.getCompany1());
        cardUserCompanyInfoDO.setDepartment(cardSaveParam.getDepartment1Name());
        cardUserCompanyInfoDO.setDepartmentEn(cardSaveParam.getDepartment1NameEn());
        cardUserCompanyInfoDO.setJob(cardSaveParam.getJob1Name());
        cardUserCompanyInfoDO.setJobEn(cardSaveParam.getJob1NameEn());
        cardUserCompanyInfoDAO.updateAll(cardUserCompanyInfoDO);
        return 1L;

    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean editCardEnterpriseEn(EnterpriseCardAddParam enterpriseCardAddParam) {
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(enterpriseCardAddParam.getUserId());
        cardUserInfoDO.setNameEn(enterpriseCardAddParam.getNameEn());
        cardUserInfoDO.setMobile(enterpriseCardAddParam.getMobile());
        cardUserInfoDO.setWechat(enterpriseCardAddParam.getWechat());
        cardUserInfoDO.setEmail(enterpriseCardAddParam.getEmail());
        cardUserInfoDO.setAddressId(enterpriseCardAddParam.getAddressId());
        cardUserInfoDO.setEnIsUpdated(1);
        Boolean flag = cardUserInfoDAO.updateSelective(cardUserInfoDO);

        updateEnterpriseCardUserCompanyInfo(enterpriseCardAddParam,cardUserInfoDO.getId());
        // 修改头像
        MemberDO memberDO = memberDAO.selectById(enterpriseCardAddParam.getMemberId());
        memberDO.setAvatarLocal(enterpriseCardAddParam.getAvatar());
        memberDAO.updateSelective(memberDO);
        return flag;
    }

    @Override
    public Boolean editPersonalCardFontColor(String color, Long userId) {
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(userId);
        cardUserInfoDO.setFontColor(color);
        return cardUserInfoDAO.updateSelective(cardUserInfoDO);
    }

    @Override
    public DemoCardDTO demoCard1() {
        String jsonStr = "{\"name_zh\":\"\\u674e\\u623f\",\"name_en\":\"Nice House\",\"font_colour\":\"FFF\",\"mobile_1\":\"15267008822\",\"cover_info\":{\"name\":\"\\u9ed1\",\"cover\":\"card\\/2018\\/07\\/03\\/406c2c2bfa78b0e173bb40055854055e.png\"},\"media_info\":{\"title\":\"\\u674e\\u623f\\u540d\\u7247\\u80cc\\u666f\\u89c6\\u9891\",\"cover\":\"card\\/2018\\/07\\/03\\/114b8826cc0eaa72771f618afa9b11f0.png\",\"file_path\":\"transcode\\/55eca14716cda1400b6408016b0e1875\\/f08173213de516d2b27b477af970c86d.mp4\"},\"logo1_info\":{\"name\":\"86900fb375fcc89ee641b7bbd06299dd.png\",\"img\":\"card\\/2020\\/03\\/10\\/9044f4c091c148e83b799c400b4730b0.png\"},\"company_1_info\":{\"name_zh\":\"\\u5927\\u5e02\\u573a\\u4e2d\\u5fc3\",\"name_en\":\"Marketing\"},\"job_1_info\":{\"name_zh\":\"\\u8425\\u9500\\u603b\\u76d1\",\"name_en\":\"Marketing Director\"},\"address_info\":{\"address_zh\":\"\\u65b0\\u7586\\u7ef4\\u543e\\u5c14\\u81ea\\u6cbb\\u533a\\u4e4c\\u9c81\\u6728\\u9f50\\u5e02\\u53cb\\u597d\\u5317\\u8def19\\u53f7\",\"address_en\":\"No. 19 , Youhao North Road, Wulumuqi City, Xinjiangweiwuerzizhi District\"},\"enterprise_info\":{\"media\":\"https:\\/\\/ivetest.ctrlvideo.com\\/game#5923739505466261\",\"media_border\":\"card\\/2020\\/03\\/09\\/6cca94db8fa5832d4552f230cfd1b2ea.png\",\"cover\":\"card\\/2020\\/03\\/09\\/c0fac525ad0019e924ae08b525609f03.png\",\"player_cover\":\"card\\/2020\\/03\\/09\\/5dd32fc6749868efbf2c17f51023c555.png\",\"contact_button\":\"card\\/2020\\/02\\/17\\/9332c8bb34b9c9c06bbc6483a87e1922.png\",\"jump_button\":\"card\\/2020\\/03\\/09\\/0026a3cc125b23c07650b88f8b166e3f.png\",\"card_cover\":\"transcode\\/83f1c9f2d3d72e4fdd58b3cfdfb0214b\\/f0838cefad849c51c8b75e03d937be6a.mp4\",\"contact_us\":\"15267008822\"}}";
        return SerialUtil.json2Object(jsonStr, DemoCardDTO.class);
    }

    @Override
    public DemoCardDTO demoCard2() {
        String jsonStr = "{\"name_zh\":\"\\u4e8c\\u66f4\\u541b\",\"mobile_1\":66666666666,\"font_colour\":\"FFF\",\"cover_info\":{\"name\":\"\\u9ed1\",\"cover\":\"card\\/2018\\/07\\/03\\/c9e441bc15f952cc5391699a9e105e12.png\"},\"media_info\":{\"title\":\"\\u540d\\u7247\\u80cc\\u666f\\u89c6\\u9891\",\"cover\":\"card\\/2020\\/04\\/10\\/519dcb8c00bd7d017730a493368bb0d4.jpg\",\"file_path\":\"transcode\\/1839ab3ff318c37d6c895d13acfc27c4\\/93d3655cc0d8b138f04988fbf5c87dc1.mp4\"},\"logo1_info\":{\"name\":\"c9e441bc15f952cc5391699a9e105e12.png\",\"img\":\"card\\/2018\\/07\\/03\\/c9e441bc15f952cc5391699a9e105e12.png\"},\"company_1_info\":{\"name_zh\":\"\\u676d\\u5dde\\u4e8c\\u66f4\\u7f51\\u7edc\\u79d1\\u6280\\u6709\\u9650\\u516c\\u53f8\",\"name_en\":\"ergeng\"},\"job_1_info\":{\"name_zh\":\"\\u5bfc\\u6f14\\u7cfb\",\"name_en\":\"Director Department\"},\"address_info\":{\"address_zh\":\"\\u6d59\\u6c5f\\u7701\\u676d\\u5dde\\u5e02\\u6587\\u4e00\\u897f\\u8def\\u4e0e\\u5d07\\u4e49\\u8def\\u4ea4\\u53c9\\u53e3\\u90e1\\u539f\\u516c\\u5143\\u91cc16\\u5e62\",\"address_en\":\"Building 16, Yuanyuanli, Junction of Wenyi West Road and Chongyi Road, Hangzhou City, Zhejiang Province\"},\"enterprise_info\":{\"media\":\"card\\/2020\\/04\\/10\\/f185d0b33f28db450d0d6f69c38322c8.mp4\",\"media_border\":\"card\\/2020\\/04\\/10\\/364f15df7b5cd2d0690c853e72f7ca75.png\",\"cover\":\"card\\/2020\\/04\\/10\\/e3e02c5e9fed2af904720c6dc12dd792.png\",\"player_cover\":\"card\\/2020\\/04\\/10\\/a7fad97ddc45156d00559b0fa228fcb2.png\",\"contact_button\":\"card\\/2020\\/02\\/17\\/9332c8bb34b9c9c06bbc6483a87e1922.png\",\"jump_button\":\"card\\/2020\\/04\\/10\\/3cebbd514d5c6aa07b29312d55af8ae7.png\",\"contact_us\":\"15267008822\"}}";
        return SerialUtil.json2Object(jsonStr, DemoCardDTO.class);
    }

    @Override
    public DemoCardDTO demoCard3() {
        String jsonStr = "\n" +
                "{\"name_zh\":\"\\u5c48\\u539f\",\"name_en\":\"\",\"font_colour\":\"FFF\",\"mobile_1\":\"\",\"mobile\":\"18357155692\",\"cover_info\":{\"name\":\"\\u9ed1\",\"cover\":\"card\\/2018\\/07\\/03\\/406c2c2bfa78b0e173bb40055854055e.png\"},\"media_info\":{\"title\":\"\\u6682\\u65e0\",\"cover\":\"\",\"file_path\":\"transcode\\/de526f6b7dbdc009f71b99f82f24f864\\/b5888b753f988a434f7076a423c3cc6c.mp4\"},\"logo1_info\":{\"id\":37,\"name\":\"1.png\",\"img\":\"card\\/2020\\/06\\/23\\/dad1c372f093ab547861536d79c6d270.png\"},\"company_1_info\":{\"name_zh\":\"\\u695a\\u56fd \\u90e2\\u57ce\",\"name_en\":\"Xinjiang International Travel Agency\"},\"job_1_info\":{\"type\":77,\"name_zh\":\"\\u5de6\\u5f92\\/\\u4e09\\u95fe\\u5927\\u592b\\/\\u8bd7\\u4eba\",\"name_en\":\"Business Manager\"},\"department_1_info\":{\"type\":77,\"name_zh\":\"\\u7ea6\\u516c\\u5143\\u524d340-\\u516c\\u5143\\u524d278\\u5e74\",\"name_en\":\"Business Manager\"},\"works_info\":{\"type\":77,\"name_zh\":\"\\u300a\\u79bb\\u9a9a\\u300b\\u300a\\u4e5d\\u6b4c\\u300b\\u300a\\u4e5d\\u7ae0\\u300b\\u300a\\u5929\\u95ee\\u300b\",\"name_en\":\"Business Manager\"},\"address_info\":{\"id\":18,\"address_zh\":\"\\u90e2\\u57ce\",\"address_en\":\"No. 19 , Youhao North Road, Wulumuqi City, Xinjiangweiwuerzizhi District\"},\"enterprise_info\":{\"media\":\"card\\/2020\\/06\\/23\\/550fad0016c39cce99d576c9c0efa9f8.mp4\",\"media_border\":\"card\\/2020\\/02\\/17\\/c02de55ec1dc91ea97f87dec469ad87c.png\",\"cover\":\"card\\/2020\\/06\\/23\\/ffcad91c5ac0a23b87381f7247265153.png\",\"player_cover\":\"card\\/2020\\/02\\/17\\/492f0486db083bb0c5c70fd46b2342c5.jpg\",\"contact_button\":\"card\\/2020\\/02\\/17\\/9332c8bb34b9c9c06bbc6483a87e1922.png\",\"jump_button\":\"card\\/2020\\/02\\/17\\/6c3c256fc19a0c5e7b9c95ed0deb0ee3.png\",\"card_cover\":\"card\\/2018\\/07\\/03\\/a1cc9d12f009a7d5b61c99e96a144888.mp4\",\"contact_us\":\"18357155692\"}}";
        return SerialUtil.json2Object(jsonStr, DemoCardDTO.class);
    }

    @Override
    public CardInfoDetailDTO cardInfoDetail(Long userId, Long oldPersonalUserId, Long oldEnterpriseUserId) {
        CardInfoDetailDTO resultDTO = new CardInfoDetailDTO();
        //id参数兼容老版本
        if (userId == null || userId == 0) {
            if (oldPersonalUserId != null && oldPersonalUserId != 0) {
                userId = userDAO.selectPersonalUserIdByOldId(oldPersonalUserId);
            } else if (oldEnterpriseUserId != null && oldEnterpriseUserId != 0) {
                userId = userDAO.selectEnterpriserUserIdByOldId(oldEnterpriseUserId);
            }
        }
        UserDO userDO = userDAO.selectById(userId);
        if (userDO == null || userDO.getIsDelete() == 1) {
            throw new BusinessErrorException(BusinessCode.CARD_DELETE);
        }
        //用户信息
        CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(userId);
        resultDTO.setUserId(userId);
        resultDTO.setName(cardUserInfoDO.getName());
        resultDTO.setNameEn(cardUserInfoDO.getNameEn());
        resultDTO.setWechat(cardUserInfoDO.getWechat());
        resultDTO.setEmail(cardUserInfoDO.getEmail());
        resultDTO.setFontColor(cardUserInfoDO.getFontColor());
        resultDTO.setZhIsUpdated(cardUserInfoDO.getZhIsUpdated());
        resultDTO.setEnIsUpdated(cardUserInfoDO.getEnIsUpdated());
        resultDTO.setMobile(cardUserInfoDO.getMobile() == null ? "" : cardUserInfoDO.getMobile());
        //头像
        MemberDO memberDO = memberDAO.selectById(userDO.getMemberId());
        if (memberDO == null) {
            resultDTO.setAvatar(StringUtils.EMPTY);
            resultDTO.setMemberId(0L);
        } else {
            resultDTO.setAvatar(memberDO.getAvatarLocal());
            resultDTO.setMemberId(memberDO.getId());
        }
        EnterpriseDO enterpriseDO = enterpriseDAO.selectById(userDO.getEnterpriseId());
        if(null != enterpriseDO) {
            resultDTO.setIsOpen(enterpriseDO.getIsOpen());
        }
        //获取该用户所有名片ID
        List<CardListDTO> cardIdList;
        if (userDO.getEnterpriseId() == 0) {
            cardIdList = cardDAO.selectIdListByUserId(userId);
        } else {
            cardIdList = cardDAO.selectIdListByEnterpriseId(userDO.getEnterpriseId());
            if (CollectionUtils.isEmpty(cardIdList)) {
                //兼容企业未设置统一名片
                cardIdList = cardDAO.selectIdListByUserId(userId);
            }
        }
        if (userDO.getEnterpriseId() == 0) {
            CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectByUserId(userId);
            if (cardBaseInfoDO != null) {
                TemplateDO templateDO = templateDAO.selectById(cardBaseInfoDO.getTemplateId());
                resultDTO.setTemplateName(templateDO.getTitle());
            }
        }
        if(CollectionUtils.isNotEmpty(cardIdList)) {
            List<CardListResponse> cardListResponses = new ArrayList<>();
            DataConvertUtils.convertDOList2DTOList(cardIdList, cardListResponses, CardListResponse.class);
            resultDTO.setCardIdList(cardListResponses);
        }
        //地址信息
        AddressDO addressDO = addressDAO.selectById(cardUserInfoDO.getAddressId());
        if (addressDO == null) {
            resultDTO.setAddress(StringUtils.EMPTY);
            resultDTO.setAddressEn(StringUtils.EMPTY);
            resultDTO.setLatitude(StringUtils.EMPTY);
            resultDTO.setLongitude(StringUtils.EMPTY);
        } else {
            resultDTO.setAddressId(addressDO.getId());
            resultDTO.setAddress(addressDO.getAddressZh());
            resultDTO.setAddressEn(addressDO.getAddressEn());
            resultDTO.setLatitude(addressDO.getLatitude());
            resultDTO.setLongitude(addressDO.getLongitude());
        }
        //获取公司信息
        List<CardInfoDetailDTO.CompanyInfoBean> companyInfoBeanList = new ArrayList<>();
        List<CardUserCompanyInfoDO> cardUserCompanyInfoDOList = cardUserCompanyInfoDAO.selectByCardUserInfoId(cardUserInfoDO.getId());
        if (cardUserCompanyInfoDOList != null && cardUserCompanyInfoDOList.size() > 0) {
            for (CardUserCompanyInfoDO cardUserCompanyInfoDO : cardUserCompanyInfoDOList) {
                CardInfoDetailDTO.CompanyInfoBean companyInfoBean = new CardInfoDetailDTO.CompanyInfoBean();
                companyInfoBean.setDepartment(cardUserCompanyInfoDO.getDepartment());
                companyInfoBean.setDepartmentEn(cardUserCompanyInfoDO.getDepartmentEn());
                companyInfoBean.setJob(cardUserCompanyInfoDO.getJob());
                companyInfoBean.setJobEn(cardUserCompanyInfoDO.getJobEn());
                companyInfoBean.setCompanyId(cardUserCompanyInfoDO.getCompanyId());
                companyInfoBean.setId(cardUserCompanyInfoDO.getId());

                CompanyDO companyDO = companyDAO.selectById(cardUserCompanyInfoDO.getCompanyId());
                if (companyDO != null) {
                    companyInfoBean.setName(companyDO.getName());
                    companyInfoBean.setNameEn(companyDO.getNameEn());
                } else {
                    companyInfoBean.setName(StringUtils.EMPTY);
                    companyInfoBean.setNameEn(StringUtils.EMPTY);
                }
                companyInfoBeanList.add(companyInfoBean);
            }
        }
        resultDTO.setCompanyInfo(companyInfoBeanList);

        resultDTO.setAppid(StringUtils.EMPTY);
        resultDTO.setPages(StringUtils.EMPTY);
        resultDTO.setIsBinding(0);
        //如果是企业名片，获取名片小程序信息
        if (userDO.getEnterpriseId() > 0) {
            WxappDO wxappDO = wxappDAO.selectByEnterpriseId(userDO.getEnterpriseId());
            if (wxappDO != null) {
                resultDTO.setIsBinding(wxappDO.getIsBinding());
                resultDTO.setAppid(wxappDO.getAppid());
                resultDTO.setPages(wxappDO.getPages());
            }
        }
        return resultDTO;
    }

    @Override
    public List<CardMaterialDetailDTO> cardMaterialDetail(Long cardId) {
        List<CardMaterialDetailDTO> resultDTO = new ArrayList<>();
        CardDO cardDO = cardDAO.selectById(cardId);
        if (cardDO == null || cardDO.getIsDelete().equals(DeleteEnum.YES.getValue())) {
            throw new BusinessErrorException(BusinessCode.CARD_NOT_EXIST);
        }
        //用户信息
        CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectById(cardDO.getBaseInfoId());
        if (cardBaseInfoDO == null || cardBaseInfoDO.getIsDelete() == 1) {
            throw new BusinessErrorException(BusinessCode.CARD_NOT_EXIST);
        }
        String[] materialIds = cardBaseInfoDO.getMaterialIds().split(",");
        List<Long> materialIdList = new ArrayList<>();
        for (String materialId : materialIds) {
            materialIdList.add(Long.valueOf(materialId));
        }
        TemplateDO templateDO = templateDAO.selectById(cardBaseInfoDO.getTemplateId());
        if(null != templateDO) {
            List<String> partList = JSON.parseArray(templateDO.getContent(),String.class);
            //定义一个map
            Map<String ,List<Integer>> map = new HashMap<>();
            map.put(SystemConstants.MAP_EKY_CARD, Arrays.asList(MaterialTypeEnum.CARD_BACKGROUND_VEDIO.getValue(),
                    MaterialTypeEnum.PICTURE.getValue(),MaterialTypeEnum.LOGO.getValue()));
            map.put(SystemConstants.MAP_EKY_VIDEO, Arrays.asList(MaterialTypeEnum.ENTERPRISE_PROPAGATE_VEDIO.getValue(),
                    MaterialTypeEnum.PROPAGATE_VEDIO_BACKGROUND_PICATURE.getValue()));
            map.put(SystemConstants.MAP_EKY_IMAGE, Arrays.asList(MaterialTypeEnum.LONG_PICTURE.getValue()));
            map.put(SystemConstants.MAP_EKY_VERTICAL_VIDEO, Arrays.asList(MaterialTypeEnum.LOGO.getValue(), MaterialTypeEnum.ENDWAYS_VEDIO.getValue()));
            map.put(SystemConstants.MAP_EKY_HORIZONTAL_VIDEO,Arrays.asList(MaterialTypeEnum.HORIZONTAL_PICTURE.getValue()));
            for (String part : partList) {
                List<Integer> typeList = map.get(part);
                List<MaterialDO> materialDOList = materialDAO.selectByMaterialIdAndType(materialIdList,typeList);
                List<CardMaterialDetailDTO.MaterialBean> materialBeans = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(materialDOList)) {
                    DataConvertUtils.convertDOList2DTOList(materialDOList, materialBeans, CardMaterialDetailDTO.MaterialBean.class);
                }
                CardMaterialDetailDTO enterpriseCardMaterialDetailDTO = new CardMaterialDetailDTO();
                enterpriseCardMaterialDetailDTO.setPart(part);
                enterpriseCardMaterialDetailDTO.setMaterial(materialBeans);
                resultDTO.add(enterpriseCardMaterialDetailDTO);
            }
        }
        return resultDTO;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Long addEnterpriseCard(EnterpriseCardRequest enterpriseCardRequest) {
        //新增敏感词审核
        if (StringUtils.isNotEmpty(enterpriseCardRequest.getTitle())) {
            List<String> contentList = new LinkedList<>();
            contentList.add(enterpriseCardRequest.getTitle());
            String checkResult = contentCheckManager.textCheck(contentList,enterpriseCardRequest.getEnterpriseId(),SourceTypeEnum.ENTERPRISE_BACKEND.getValue());
            if (checkResult.equals("block")) {
                throw new BusinessErrorException(BusinessCode.CONTAIN_SENSITIVE_WORDS);
            }
        }
        // 查询企业名片是否超过上限
        Long enterpriseId = enterpriseCardRequest.getEnterpriseId();
        List<CardListDTO> cardListDTOS = cardDAO.selectIdListByEnterpriseId(enterpriseId);
        if(CollectionUtils.isNotEmpty(cardListDTOS) && cardListDTOS.size() >= 7) {
            return 0L;
        }
        log.info("CardManager.addEnterpriseCard 新增企业名片 : {}", JSON.toJSONString(enterpriseCardRequest));
        // 构建cardBaseInfo
        CardBaseInfoDO cardBaseInfoDO = new CardBaseInfoDO();
        cardBaseInfoDO.setEnterpriseId(enterpriseCardRequest.getEnterpriseId());
        cardBaseInfoDO.setTemplateId(enterpriseCardRequest.getTemplateId());
        if(CollectionUtils.isNotEmpty(enterpriseCardRequest.getMaterialIds())) {
            cardBaseInfoDO.setMaterialIds(String.join(",", enterpriseCardRequest.getMaterialIds().
                    stream().map(String::valueOf).collect(Collectors.toList())));
        }
        if(null != enterpriseCardRequest.getComponentId()) {
            cardBaseInfoDO.setComponentId(enterpriseCardRequest.getComponentId());
        }
        Long cardBaseInfoId = cardBaseInfoDAO.insertSelective(cardBaseInfoDO);
        log.info("CardManager.addEnterpriseCard 新增企业名片基础信息成功 基础信息id是 : {}", cardBaseInfoId);
        // 构建cardDO
        CardDO cardDO = new CardDO();
        if(null != enterpriseCardRequest.getComponentId()) {
            cardDO.setTitle(enterpriseCardRequest.getTitle());
        } else {
            cardDO.setTitle(enterpriseCardRequest.getTitle());
        }
        cardDO.setEnterpriseId(enterpriseCardRequest.getEnterpriseId());
        cardDO.setTitle(enterpriseCardRequest.getTitle());
        cardDO.setEnterpriseId(enterpriseCardRequest.getEnterpriseId());
        cardDO.setBaseInfoId(cardBaseInfoId);
        Long cardId = cardDAO.insertSelective(cardDO);
        log.info("CardManager.addEnterpriseCard 新增企业名片成功 企业名片id是 : {}", cardId);
        return cardId;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Integer deleteEnterpriseCard(EnterpriseCardRequest enterpriseCardRequest) {
        // 校验是否是最后一条
        List<CardListDTO> cardListDTOS = cardDAO.selectIdListByEnterpriseId(enterpriseCardRequest.getEnterpriseId());
        if(CollectionUtils.isNotEmpty(cardListDTOS) && cardListDTOS.size() == 1) {
            return -1;
        }
        log.info("CardManager.deleteEnterpriseCard 删除企业名片 名片id是 : {}", enterpriseCardRequest.getId());
        // 查询名片信息
        CardDO cardDO = cardDAO.selectById(enterpriseCardRequest.getId());
        Long baseInfoId = cardDO.getBaseInfoId();
        // 删除cardBaseInfo
        cardBaseInfoDAO.deleteById(baseInfoId);
        // 删除card
        cardDO.setIsDelete(1);
        return cardDAO.updateSelective(cardDO) ? 1 : 0;
    }

    @Override
    public Boolean updateEnterpriseCardName(EnterpriseCardRequest enterpriseCardRequest) {
        //新增敏感词审核
        if (StringUtils.isNotEmpty(enterpriseCardRequest.getTitle())) {
            List<String> contentList = new LinkedList<>();
            contentList.add(enterpriseCardRequest.getTitle());
            String checkResult = contentCheckManager.textCheck(contentList,enterpriseCardRequest.getEnterpriseId(),SourceTypeEnum.ENTERPRISE_BACKEND.getValue());
            if (checkResult.equals("block")) {
                throw new BusinessErrorException(BusinessCode.CONTAIN_SENSITIVE_WORDS);
            }
        }
        log.info("CardManager.updateEnterpriseCardName 修改企业名片 修改的内容是 : {}", JSON.toJSONString(enterpriseCardRequest));
        CardDO cardDO = new CardDO();
        cardDO.setId(enterpriseCardRequest.getId());
        cardDO.setTitle(enterpriseCardRequest.getTitle());
        return cardDAO.updateSelective(cardDO);
    }

    @Override
    public Pager<EnterpriseCardResponse> list(EnterpriseCardRequest enterpriseCardRequest) {
        log.info("CardManager.list 分页查询企业名片列表 查询参数是 : {}", JSON.toJSONString(enterpriseCardRequest));
        Integer offset = (enterpriseCardRequest.getPage()-1) * enterpriseCardRequest.getPageSize();
        Integer size = enterpriseCardRequest.getPageSize();
        log.info("CardManager.list 分页查询企业名片列表 offset : {}, pageSize :  {}", offset, size);
        Integer count = cardDAO.enterpriseCardCount(enterpriseCardRequest.getTitle(), enterpriseCardRequest.getEnterpriseId());
        log.info("CardManager.list 查询的条数是 count : {}", count);
        List<EnterpriseCardResult> enterpriseCardResults = cardDAO.queryEnterpriseCard(enterpriseCardRequest.getTitle(), offset, size, enterpriseCardRequest.getEnterpriseId());
        log.info("CardManager.list 查询的结果是 enterpriseCardResults : {}", JSON.toJSONString(enterpriseCardResults));
        if(CollectionUtils.isNotEmpty(enterpriseCardResults)) {
            List<EnterpriseCardResponse> enterpriseCardResponseList = new ArrayList<>();
            DataConvertUtils.convertDOList2DTOList(enterpriseCardResults, enterpriseCardResponseList, EnterpriseCardResponse.class);
            return new Pager<>(enterpriseCardRequest.getPage(), enterpriseCardRequest.getPageSize(),
                    count, enterpriseCardResponseList);
        }
        return new Pager<>(enterpriseCardRequest.getPage(), enterpriseCardRequest.getPageSize(),
                count, new ArrayList<>());
    }
}
